<?php

namespace app\api\controller\wanlshop;

use addons\ymyauexpress\library\Express;
use addons\ymyauexpress\library\Expressty;
use app\admin\model\wanlshop\Packagerule;
use app\api\model\wanlshop\Goods;
use app\common\controller\Api;
use think\Cache;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * WanlShop订单接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['replenishorder'];
    protected $noNeedRight = ['*'];

    /**
     * 获取订单列表
     *
     * @ApiSummary  (WanlShop 订单接口获取订单列表)
     * @ApiMethod   (GET)
     * 2020年5月12日23:25:40
     *
     * @param string $state 状态
     */
    public function getOrderList()
    {

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $state = $this->request->request('state');
        if ($state && $state != 0) {
            $where['state'] = $state;
        }
        $where['status'] = 'normal';
        $where['user_id'] = $this->auth->id;
        $where['shop_id'] = $this->shop_id;
        // 列表
        $list = model('app\api\model\wanlshop\Order')
            ->where($where)
            ->field('id,shop_id,state,freight_type,createtime')
            ->order('updatetime desc')
            ->paginate()
            ->each(function ($order, $key) {
                $goods = model('app\api\model\wanlshop\OrderGoods')
                    ->where(['order_id' => $order->id])
                    ->field('id,title,order_id,image,difference,price,market_price,number,refund_status')
                    ->select();
                foreach ($goods as $key=>$value){
                    $package = Db::name('wanlshop_package_goods')->where('order_id',$value['order_id'])->where('order_goods_id',$value['id'])->value('package_id');
                    $p = Db::name('wanlshop_package')->where('id',$package)->value('image');
                    $goods[$key]['pageage'] = empty($p)?"":request()->host().$p;
                }

                $order['goods'] = $goods;
                $order['pay'] = $order->pay ? $order->pay->visible(['number', 'price', 'order_price', 'freight_price', 'discount_price', 'actual_payment']) : [];
                $order['shop'] = $order->shop ? $order->shop->visible(['shopname', 'image']) : [];

                return $order;
            });
        $list ? ($this->success('ok', $list)) : ($this->error(__('网络繁忙')));
    }

    /**
     * 查询用户店铺订单记录
     *
     * @ApiSummary  (查询用户店铺订单记录 1.0.2升级)
     * @ApiMethod   (POST)
     *
     * @param string $shop_id 店铺ID
     */
    public function getOrderListToShop()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $shop_id = $this->request->post('shop_id');
            $shop_id ? '' : ($this->error(__('Invalid parameters')));
            $list = model('app\api\model\wanlshop\Order')
                ->where(['shop_id' => $shop_id, 'user_id' => $this->auth->id, 'status' => 'normal'])
                ->field('id,shop_id,order_no,state')
                ->order('updatetime desc')
                ->select();
            // 订单状态:1=待支付,2=待发货,3=待收货,4=待评论,5=售后订单(已弃用),6=已完成,7=已取消
            foreach ($list as $row) {
                $row['goods'] = model('app\api\model\wanlshop\OrderGoods')
                    ->where(['order_id' => $row->id])
                    ->field('id,title,image,difference,price,market_price,number,refund_status')
                    ->select();
            }
            $this->success(__('发送成功'), $list);
        }
        $this->error(__('Illegal request'));
    }

    /**
     * 获取订单详情
     *
     * @ApiSummary  (WanlShop 订单接口获取订单详情)
     * @ApiMethod   (GET)
     *
     * @param string $id 订单ID
     */
    public function getOrderInfo()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $id = $this->request->request('id');
        $id ? $id : ($this->error(__('Illegal request')));
        $order = model('app\api\model\wanlshop\Order')
            ->where(['id' => $id, 'user_id' => $this->auth->id])
            ->field('id,shop_id,order_no,isaddress,express_no,express_name,freight_type,state,createtime,paymenttime,delivertime,taketime,dealtime,delivery_mode')
            ->find();
        $order ? $order : ($this->error(__('网络异常')));
        // 输出配置
        $config = get_addon_config('wanlshop');
        $order['config'] = $config['order'];
        switch ($order['state']) {
            case 1:
                $express = [
                    'context' => '付款后，即可将宝贝发出',
                    'status' => '尚未付款',
                    'time' => date('Y-m-d H:i:s', $order['createtime'])
                ];
                break;
            case 2:
                $express = [
                    'context' => '商家正在处理订单',
                    'status' => '已付款',
                    'time' => date('Y-m-d H:i:s', $order['paymenttime'])
                ];
                break;
            default: // 获取物流
                /*$data = Cache::get($order['express_no'].'_track');
                if(!$data){
                    if($order['delivery_mode'] == 'instead'){
                        $config = get_addon_config('ymyauexpress');
                    }else{
                        $config = model('app\index\model\wanlshop\ShopConfig')
                            ->field('au_member_id,au_password')
                            ->where('shop_id',$order['shop_id'])
                            ->find();
                    }
                    $express = new Express($config['au_member_id'],$config['au_password']);
                    $data = $express->track(['OrderId'=>$order['express_no']]);
                    $data = array_reverse($data);
                    Cache::set($order['express_no'].'_track',$data,600);
                }
				if($data){
                    $express = [
                        'status' => '已发货',
                        'context' => $data[0]['StatusDetail'],
                        'time' => $data[0]['StatusTime']
                    ];
				}else{
					$express = [
						'status' => '已发货',
						'context' => '包裹等待揽收~',
						'time' => date('Y-m-d H:i:s', $order['delivertime'])
					];
				}*/
                $express = [
                    'status' => '已发货',
                    'context' => '包裹等待揽收~',
                    'time' => date('Y-m-d H:i:s', $order['delivertime'])
                ];
        }
        // 获取物流
        $order['logistics'] = $express;
        // 获取地址
        $order['address'] = model('app\api\model\wanlshop\OrderAddress')
            ->where(['order_id' => $id, 'user_id' => $this->auth->id])
            ->order('isaddress desc')
            ->field('id,address_id,name,mobile,address,address_name,number,image_front,image_back')
            ->find();


        if (empty($order['address']['image_front'])) {

            $order['address']['need_replenish'] = 1;
        } else {
            // $order['address']->need_replenish = 1;
            $order['address']['need_replenish'] = 0;
        }

        // 获取店铺
        $order['shop'] = $order->shop ? $order->shop->visible(['shopname']) : [];
        // 获取订单商品
        $order['goods'] = model('app\api\model\wanlshop\OrderGoods')
            ->where(['order_id' => $id])
            ->field('id,goods_id,title,image,difference,price,market_price,actual_payment,discount_price,freight_price,number,refund_id,refund_status')
            ->select();
        // 订单包裹信息
        $order['package'] = model('app\api\model\wanlshop\Package')
            ->with(['goods'])
            ->field('id,order_id,package_no,express_name,express_no,delivery_status,image,freight_price,package_price')
            ->where('order_id', $order['id'])
            ->select();

        $order['package_image'] = [];



      // dump(json_decode(json_encode($order['package'],JSON_UNESCAPED_UNICODE)));die;

        if(!empty($order['package'])){
            foreach ($order['package'] as $key => $value){
                $order['package_image'] = array_merge($order['package_image'],$value['image']);
            }
        }


//        $goods = model('app\api\model\wanlshop\OrderGoods')
//            ->where(['order_id' => $order->id])
//            ->field('id,title,order_id,image,difference,price,market_price,number,refund_status')
//            ->select();
//        foreach ($goods as $key=>$value){
//            $package = Db::name('wanlshop_package_goods')->where('order_id',$value['order_id'])->where('order_goods_id',$value['id'])->value('package_id');
//            $p = Db::name('wanlshop_package')->where('id',$package)->value('image');
//            $goods[$key]['pageage'] = empty($p)?"":request()->host().$p;
//        }


        // 获取支付
        $order['pay'] = $order->pay ? $order->pay->visible(['id', 'pay_no', 'number', 'price', 'order_price', 'freight_price', 'discount_price', 'actual_payment']) : [];
        $this->success('ok', $order);
    }

    // 获取包裹详情
    public function getPackageInfo()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $package_no = $this->request->param('package_no');
        $package_no ? $package_no : ($this->error(__('Illegal request')));
        $package = model('app\api\model\wanlshop\Package')
            ->with(['goods'])
            ->field('id,order_id,package_no,express_name,express_no,delivery_status,image,freight_price,package_price')
            ->where(function ($query) use ($package_no) {
                $query->where('express_no', $package_no)
                    ->whereOr('package_no', $package_no);
            })
            ->find();
        $package ? $package : ($this->error(__('网络异常')));
        $this->success('ok', $package);
    }

    // 上传包裹照片
    public function uploadImage()
    {
        $images = $this->request->post('images');
        $package_no = $this->request->post('package_no');
        $package_no ? $package_no : ($this->error(__('Illegal request')));
        $package = model('app\api\model\wanlshop\Package')->where(function ($query) use ($package_no) {
            $query->where('express_no', $package_no)
                ->whereOr('package_no', $package_no);
        })->find();
        $package->image = $images;
        $package->save();
        $this->success('ok');
    }

    /**
     * 确认收货
     *
     * @ApiSummary  (WanlShop 订单接口确认收货)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID                       ------ 后续版本优化 Db::startTrans();
     */
    public function confirmOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('Illegal request')));
            $order = false;
            // 判断权限
            try {
                $order = model('app\api\model\wanlshop\Order')->confirm($id, 'user');
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }

            $this->success('ok', $order ? true : false);
        }
        $this->error(__('Illegal request'));
    }

    /**
     * 取消订单
     *
     * @ApiSummary  (WanlShop 订单接口取消订单)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function cancelOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('Illegal request')));
            // 判断权限
            $this->getOrderState($id) != 1 ? ($this->error(__('订单异常'))) : '';
            $row = model('app\api\model\wanlshop\Order')->get(['id' => $id, 'user_id' => $this->auth->id]);
            $result = $row->allowField(true)->save(['state' => 7]);
            // 还原优惠券 1.0.2升级
            if ($row['coupon_id'] != 0) {
                model('app\api\model\wanlshop\CouponReceive')->where(['id' => $row['coupon_id'], 'user_id' => $this->auth->id])->update(['state' => 1]);
            }
            // 释放库存 1.0.3升级
            foreach (model('app\api\model\wanlshop\OrderGoods')->all(['order_id' => $row['id']]) as $vo) {
                // 查询商品是否需要释放库存
                if (model('app\api\model\wanlshop\Goods')->get($vo['goods_id'])['stock'] == 'porder') {
                    model('app\api\model\wanlshop\GoodsSku')->where('id', $vo['goods_sku_id'])->setInc('stock', $vo['number']);
                }

                //增加活动库存
                if ($vo['activity_id'] > 0 && $vo['activity'] == 'seckill') {
                    model('app\api\model\wanlshop\ActivityGoodsSku')
                        ->where('goods_id', $vo['goods_id'])
                        ->where('activity_id', $vo['activity_id'])
                        ->where('sku_id', $vo['goods_sku_id'])
                        ->dec('sales', $vo['number'])
                        ->inc('stock', $vo['number'])
                        ->update();
                }
            }
            $this->success('ok', $result ? true : false);
        }
        $this->error(__('Illegal request'));
    }

    /**
     * 删除订单
     *
     * @ApiSummary  (WanlShop 订单接口删除订单)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function delOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('Illegal request')));
            // 判断权限
            $state = $this->getOrderState($id);
            $state == 6 || $state == 7 ? '' : ($this->error(__('Illegal request')));
            $order = model('app\api\model\wanlshop\Order')
                ->save(['status' => 'hidden'], ['id' => $id]);
            $this->success('ok', $order ? true : false);
        }
        $this->error(__('Illegal request'));
    }


    /**
     * 修改地址
     *
     * @ApiSummary  (WanlShop 订单接口修改地址)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function editOrderAddress()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $order_id = $this->request->post('id');
            $address_id = $this->request->post('address_id');
            $order_id || $address_id ? $order_id : ($this->error(__('Illegal request')));
            // 判断权限
            $this->getOrderState($order_id) > 3 ? ($this->error(__('订单异常'))) : '';
            // 订单
            $order = model('app\api\model\wanlshop\Order')
                ->where(['id' => $order_id, 'user_id' => $this->auth->id])
                ->find();

            //判断是否修改过
            if ($order['isaddress'] == 1) {
                $this->error(__('It\'s already been revised once'));
            } else {
                // 获取地址
                $address = model('app\api\model\wanlshop\Address')
                    ->where(['id' => $address_id, 'user_id' => $this->auth->id])
                    ->find();
                // 修改地址
                $data = model('app\api\model\wanlshop\OrderAddress')->save([
                    'user_id' => $this->auth->id,
                    'shop_id' => $order->shop_id,
                    'order_id' => $order_id,
                    'isaddress' => 1,
                    'name' => $address['name'],
                    'mobile' => $address['mobile'],
                    'address' => $address['province'] . '/' . $address['city'] . '/' . $address['district'] . '/' . $address['address'],
                    'address_name' => $address['address_name'],
                    'location' => $address['location']
                ]);
                // 修改状态
                model('app\api\model\wanlshop\Order')->where(['id' => $order_id, 'user_id' => $this->auth->id])->update(['isaddress' => 1]);
                $this->success('ok', $data);
            }
        }
        $this->error(__('Illegal request'));
    }


    /**
     * 评论订单
     *
     * @ApiSummary  (WanlShop 订单接口评论订单)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function commentOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $post ? $post : ($this->error(__('数据异常')));
            $user_id = $this->auth->id;
            // 判断权限
            $this->getOrderState($post['order_id']) != 4 ? ($this->error(__('Has already commented or the order is abnormal'))) : '';
            // 生成列表
            $commentData = [];
            foreach ($post['goodsList'] as $value) {
                $commentData[] = [
                    'user_id' => $user_id,
                    'shop_id' => $post['shop']['id'],
                    'order_id' => $post['order_id'],
                    'goods_id' => $value['goods_id'],
                    'order_goods_id' => $value['id'],
                    'state' => $value['state'],
                    'content' => $value['comment'],
                    'suk' => $value['difference'],
                    'images' => $value['imgList'],
                    'score' => round((($post['shop']['describe'] + $post['shop']['service'] + $post['shop']['deliver'] + $post['shop']['logistics']) / 4), 1),
                    'score_describe' => $post['shop']['describe'],
                    'score_service' => $post['shop']['service'],
                    'score_deliver' => $post['shop']['deliver'],
                    'score_logistics' => $post['shop']['logistics'],
                    'switch' => 0
                ];
                //评论暂不考虑并发，为列表提供好评付款率，减少并发只能写进商品中
                model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('comment');
                if ($value['state'] == 0) {
                    model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('praise');
                } else if ($value['state'] == 1) {
                    model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('moderate');
                } else if ($value['state'] == 2) {
                    model('app\api\model\wanlshop\Goods')->where(['id' => $value['goods_id']])->setInc('negative');
                }
            }
            if (model('app\api\model\wanlshop\GoodsComment')->saveAll($commentData)) {
                $order = model('app\api\model\wanlshop\Order')
                    ->where(['id' => $post['order_id'], 'user_id' => $user_id])
                    ->update(['state' => 6]);
            }
            //更新店铺评分
            $score = model('app\api\model\wanlshop\GoodsComment')
                ->where(['user_id' => $user_id])
                ->select();
            // 从数据集中取出
            $describe = array_column($score, 'score_describe');
            $service = array_column($score, 'score_service');
            $deliver = array_column($score, 'score_deliver');
            $logistics = array_column($score, 'score_logistics');
            // 更新店铺评分
            model('app\api\model\wanlshop\Shop')
                ->where(['id' => $post['shop']['id']])
                ->update([
                    'score_describe' => bcdiv(array_sum($describe), count($describe), 1),
                    'score_service' => bcdiv(array_sum($service), count($service), 1),
                    'score_deliver' => bcdiv(array_sum($deliver), count($deliver), 1),
                    'score_logistics' => bcdiv(array_sum($logistics), count($logistics), 1)
                ]);
            $this->success('ok', []);
        }
        $this->error(__('Illegal request'));
    }

    /**
     * 获取订单物流状态
     *
     * @ApiSummary  (WanlShop 订单接口获取订单物流状态)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function getLogistics()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->param('id');
            $id ? $id : ($this->error(__('Illegal request')));
            //获取订单
            $package = model('app\api\model\wanlshop\Package')
                ->where(['id' => $id, 'user_id' => $this->auth->id])
                ->find();
            $order = model('app\api\model\wanlshop\Order')->get($package['order_id']);
            // 获取快递
            switch ($order['state']) {
                case 1:
                    $list[] = [
                        'context' => '付款后，即可将宝贝发出',
                        'status' => '尚未付款',
                        'time' => date('Y-m-d H:i:s', $order['createtime'])
                    ];
                    break;
                case 2:
                    $list[] = [
                        'context' => '商家接受到您的订单，准备出库',
                        'status' => '已下单',
                        'time' => date('Y-m-d H:i:s', $order['paymenttime'])
                    ];
                    break;
                default: // 获取物流
                    $data = Cache::get($package['express_no'] . '_track');
                    if (!$data) {
                        if ($package['delivery_mode'] == 'instead') {
                            $config = get_addon_config('ymyauexpress');
                        } else {
                            $config = model('app\index\model\wanlshop\ShopConfig')
                                ->field('au_member_id,au_password')
                                ->where('shop_id', $package['shop_id'])
                                ->find();
                        }

                        if($package['express_no'][0]=="G"){
                            $express = new Expressty();
                            $data = $express->track($package['express_no']);
                            $data = array_reverse($data);
                            Cache::set($package['express_no'].'_track',$data,600);
                        }else{
                            $express = new Express($config['au_member_id'],$config['au_password']);
                            $data = $express->track(['OrderId'=>$package['express_no']]);
                            $data = array_reverse($data);
                            Cache::set($package['express_no'].'_track',$data,600);
                        }
                    }
                    if ($data) {
                        foreach ($data as $vo) {
                            $list[] = [
                                'context' => $vo['StatusDetail'],
                                'status' => "在途",
                                'time' => $vo['StatusTime']
                            ];
                        }
                    } else {
                        $list = [
                            'status' => '已发货',
                            'context' => '包裹等待揽收~',
                            'time' => date('Y-m-d H:i:s', $package['delivertime'])
                        ];
                    }


            }
            //$package['kuaidi'] = $order->kuaidi ? $order->kuaidi->visible(['name','logo','tel']) : [];
            $package['express'] = $list;
            $this->success('ok', $package);
        }
        $this->error(__('Illegal request'));
    }

    /**
     * 获取包裹物流状态
     *
     * @ApiSummary  (WanlShop 订单接口获取订单物流状态)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    public function getPackageLogistics()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $id = $this->request->post('id');
            $id ? $id : ($this->error(__('Illegal request')));
            //获取订单
            $package = model('app\api\model\wanlshop\Package')
                ->where(['id' => $id, 'user_id' => $this->auth->id])
                ->field('id,shop_id,express_name,express_no,package_no,createtime,delivertime,delivery_mode,freight_id')
                ->find();
            $freight = model('app\api\model\wanlshop\ShopFreight')->where('id', $package['freight_id'])->find();
            // 获取快递
            $data = Cache::get($package['express_no'] . '_track');
            if (!$data) {
                if ($package['delivery_mode'] == 'instead') {
                    $config = get_addon_config('ymyauexpress');
                } else {
                    $config = model('app\index\model\wanlshop\ShopConfig')
                        ->field('au_member_id,au_password')
                        ->where('shop_id', $package['shop_id'])
                        ->find();
                }


                if($package['express_no'][0]=="G"){
                    $express = new Expressty();
                    $data = $express->track($package['express_no']);
                    $data = array_reverse($data);
                    Cache::set($package['express_no'].'_track',$data,600);
                }else{
                    $express = new Express($config['au_member_id'],$config['au_password']);
                    $data = $express->track(['OrderId'=>$package['express_no']]);
                    $data = array_reverse($data);
                    Cache::set($package['express_no'].'_track',$data,600);
                }

            }
            if ($data) {
                foreach ($data as $vo) {
                    $list[] = [
                        'context' => $vo['StatusDetail'],
                        'status' => $vo['id_OrderStatus'],
                        'time' => $vo['StatusTime']
                    ];
                }
            } else {
                $list = [
                    'status' => '已发货',
                    'context' => '包裹等待揽收~',
                    'time' => date('Y-m-d H:i:s', $package['delivertime'])
                ];
            }

            $order['kuaidi'] = model('app\api\model\wanlshop\Kuaidi')->field('name,logo,tel')
                ->where(['code' => $freight['type']])->find();
            $order['express'] = $list;
            $this->success('ok', $order);
        }
        $this->error(__('Illegal request'));
    }


    /**
     * 确认订单
     *
     * @ApiSummary  (WanlShop 订单接口确认订单)
     * @ApiMethod   (POST)
     *
     * @param string $data 商品数据
     */
    public function getOrderGoodsList()
    {

//        dump(json_encode(['attachment'=>[['goods'=>[1001,102], 'phone_price'=>0.5,
//            'shox_price'=>1],['goods'=>[1003], 'phone_price'=>0.5,
//            'shox_price'=>0]]],JSON_UNESCAPED_UNICODE));die;
//
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $request = $this->request->post();
            // 订单数据
            $order = array();
            $map = array();
            $freight = model('app\api\model\wanlshop\ShopFreight')->where('id', $request['freight_id'] ?? 0)->field('id,type,delivery,isdelivery,name,valuation')->find();
            if (!$freight) {
                $freight = model('app\api\model\wanlshop\ShopFreight')->where([
                    'status' => 'normal',
                    'shop_id' => $this->shop_id,
                ])->field('id,type,delivery,isdelivery,name,valuation')->find();
            }
            $currency_rate = model('app\api\model\wanlshop\Pay')->getCurrencyRate('', 0);
            // 1.0.5升级 修复客户端地址更新
            $where = !empty($request['address_id']) ? ['id' => $request['address_id'], 'user_id' => $this->auth->id] : ['user_id' => $this->auth->id, 'default' => 1];

            // 地址
            $address = model('app\api\model\wanlshop\Address')
                ->where($where)
                ->field('id,name,mobile,province,city,district,address')
                ->find();
            // 1.0.5升级
            if ($freight['type'] != 'ziti') {
                if (!$address) $this->error(__('地址不存在'));
            }


            // 合计
            $statis = array(
                "allnum" => 0,
                "allsub" => 0,
                'allsub_rmb' => 0,
                'allweight' => 0
            );
            $goodsList = [];
            foreach ($request['data'] as $post) {


                // 商品详情
                $goods = model('app\api\model\wanlshop\Goods')
                    ->where('id', $post['goods_id'])
                    ->field('id,shop_id,shop_category_id,title,title_en,image,stock,freight_id,sales')
                    ->find();

                // 获取SKU
                $sku = model('app\api\model\wanlshop\GoodsSku')
                    ->where('id', $post['sku_id'])
                    ->field('id,difference,difference_en,price,market_price,stock,weigh,group_price,supply_price,rule_id')
                    ->find();

                // 获取SKU
                $goods['sku'] = model('app\api\model\wanlshop\GoodsSku')->getGroupSku($sku, $goods['id']);

                // 数量
                $goods['number'] = $post['number'];
                $statis['allweight'] += bcmul($sku['weigh'], $goods['number'], 2);


//                data: [{shop_id: 4, shop_name: "澳优Carnegie", goods_id: 971, title: "Swisse 清颜净肤胶原蛋白肽粉 120g",…},…]
//0: {shop_id: 4, shop_name: "澳优Carnegie", goods_id: 971, title: "Swisse 清颜净肤胶原蛋白肽粉 120g",…}
//1: {shop_id: 4, shop_name: "澳优Carnegie", goods_id: 968, title: "8分钟X-20抗菌消毒抑菌便携酒精免洗洗手喷雾120ml",…}
//2: {shop_id: 4, shop_name: "澳优Carnegie", goods_id: 1451, title: "8分钟X-20抗菌消毒抑菌便携酒精免洗洗手喷雾120ml",…}
//3: {shop_id: 4, shop_name: "澳优Carnegie", goods_id: 1450, title: "b.box 宝宝重力杯 240毫升 6个月以上",…}
//4: {shop_id: 4, shop_name: "澳优Carnegie", goods_id: 1280, title: "GOAT 山羊奶皂 100克/块",…}
//5: {shop_id: 4, shop_name: "澳优Carnegie", goods_id: 1458, title: "b.box 宝宝重力杯 240毫升 6个月以上",…}


                // 格式化
                if (empty($map[$goods['shop_id']])) {
                    $order[] = array(
                        "shop_id" => $goods['shop_id'],
                        "shop_name" => $goods->shop ? $goods->shop->visible(['shopname'])['shopname'] : [],
                        "shop_state" => $goods->shop ? $goods->shop->visible(['state'])['state'] : [],
                        "products" => [$goods],
                        "coupon" => [],
                        "freight_id" => $freight['id'],
                        "number" => $goods['number'],
                        "sub_price" => round(bcmul($sku['price'], $goods['number'], 2), 2)
                    );
                    $map[$goods['shop_id']] = $goods;
                } else {
                    // 追加1-*
                    foreach ($order as $key => $value) {
                        if ($value['shop_id'] == $goods['shop_id']) {
                            array_push($order[$key]['products'], $goods);
                            $order[$key]['number'] += $post['number'];
                            $order[$key]['sub_price'] = round(bcadd($order[$key]['sub_price'], bcmul($sku['price'], $post['number'], 2), 2), 2);
                            break;
                        }
                    }
                }
                // 所有店铺统计
                $statis['allnum'] += $goods['number'];
            }

            // 获取运费策略-店铺循环 --  检测组合套餐

            foreach ($order as $key => $value) {
                $packageFright = model('app\api\model\wanlshop\Package')->packageFright($value['products'], $freight['id'], $address['city']);
                $freightPrice = $packageFright['freightPrice'];
                /*$config = model('app\api\model\wanlshop\ShopConfig')
                    ->where('shop_id',$value['shop_id'])
                    ->find();
                if($config['freight'] == 0){
                    // 运费叠加
                    $order[$key]['freight'] = [
                        'id' => $value['freight'][0]['id'],
                        'name' => '运费叠加',
                        'price' => array_sum(array_column($value['freight'],'price'))
                    ];
                }else if($config['freight'] == 1){
                    // 以最低结算
                    array_multisort(array_column($value['freight'],'price'),SORT_ASC,$value['freight']);
                    $order[$key]['freight'] = [
                        'id' => $value['freight'][0]['id'],
                        'name' => $value['freight'][0]['name'],
                        'price' => $value['freight'][0]['price']
                    ];
                }else if($config['freight'] == 2){
                    // 以最高结算
                    array_multisort(array_column($value['freight'],'price'),SORT_DESC,$value['freight']);
                    $order[$key]['freight'] = [
                        'id' => $value['freight'][0]['id'],
                        'name' => $value['freight'][0]['name'],
                        'price' => $value['freight'][0]['price']
                    ];
                }*/
                $order[$key]['freight'] = [
                    'id' => $freight['id'],
                    'name' => $freight['name'],
                    'price' => round($freightPrice,2),

                    'packageList' => $packageFright['packageList'],

                ];
                /***检测组合套餐逻辑***/
                $package = model('app\api\model\wanlshop\Activity')->checkPackage($value, 'getOrderGoodsList');
                $order[$key]['package'] = $package;
                if ($package != false) {
                    $order[$key]['sub_price'] = $package['price'];
                }
                /***检测组合套餐逻辑***/
                $order[$key]['order_price'] = $order[$key]['sub_price'];
                // 2020年9月19日12:10:59 添加快递价格备份,用于还原运费
                $order[$key]['freight_price_bak'] = round($order[$key]['freight']['price'], 2);
                $order[$key]['sub_price'] += $order[$key]['freight']['price'];
                $order[$key]['sub_rmb_price'] = bcmul($order[$key]['sub_price'], $currency_rate, 2);
                $statis['allsub'] += $order[$key]['sub_price'];
                $statis['allsub_rmb'] = bcmul($statis['allsub'], $currency_rate, 2);
            }

            $statis['allsub'] = round($statis['allsub'], 2);
            $statis['allweight'] = round($statis['allweight'], 2);
            //$statis['allweight']

            $freightList = model('app\api\model\wanlshop\ShopFreight')
                ->where('shop_id', $this->shop_id)
                ->field('id,isdelivery,name')
                ->select();
            $services = model('app\api\model\wanlshop\Orderservice')->field('id,name,price')->where([
                'status' => 'normal'
            ])->select();
            // 地址
            $datalist['addressData'] = $address;
            $datalist['freightList'] = $freightList;
            // 订单
            $datalist['orderData']['lists'] = $order;
            $datalist['orderData']['statis'] = $statis;
            $datalist['orderData']['service'] = $services;
            $this->success('ok', $datalist);
        } else {
            $this->error(__('Illegal request'));
        }
    }

    /**
     * 提交订单
     *
     * @ApiSummary  (WanlShop 订单接口提交订单)
     * @ApiMethod   (POST)
     *
     * @param string $data 数组
     */
    public function addOrder()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $result = false;
            $params = $this->request->post();
            $attachment_price = 0;
            if (empty($params['attachment'])) {
                $params['attachment'] = [];
            } elseif (!empty($params['attachment'])) {
                foreach ($params['attachment'] as $a_v) {
                    $attachment_price += ($a_v['phone_price'] + $a_v['shox_price']);
                }
            }
           // dump($params);
         //  dump($params['freight_id']);die;//freight_id

            $freight = model('app\api\model\wanlshop\ShopFreight')->where('id', $params['freight_id'] ?? 0)->field('id,delivery,isdelivery,name,valuation')->find();
            if (!$freight) {
                $freight = model('app\api\model\wanlshop\ShopFreight')->where([
                    'type' => 'au',
                    'shop_id' => $this->shop_id,
                ])->field('id,delivery,isdelivery,name,valuation')->find();
            }
            $user_id = $this->auth->id; // 用户ID
            $addressList = [];
            $goodsList = [];
            $payList = [];
            // 1.0.6升级 修复跨店累加
            // $priceAll = 0; // 总价格
            // $numberAll = 0; // 总数量
            // $freightALL = [];
            // $coupon_price = 0; //优惠券金额
            // $discount_price = 0; // 优惠金额，因为后续版本涉及到活动减免，所以优惠金额要单独拎出来
            // 判断是否有地址 1.0.2升级
            if (array_key_exists('address_id', $params['order'])) {
                $address_id = $params['order']['address_id']; // 地址ID
            } else {
                $this->error(__('Please click the top to add the shipping address'));
            }
            // 判断订单是否合法 1.0.4升级
            if (array_key_exists('lists', $params['order'])) {
                $lists = $params['order']['lists'];
                if (!isset($lists) && count($lists) == 0) {
                    $this->error('ERR001：' . __('Order abnormal, please return to reorder'));
                }
            } else {
                $this->error('ERR002：' . __('Order abnormal, please return to reorder'));
            }
            // 查询地址
            $address = model('app\api\model\wanlshop\Address')
                ->where(['id' => $address_id, 'user_id' => $user_id])
                ->find();

            // 1.0.4升级
            if (!isset($address)) {
                $this->error(__('The address is abnormal. It was not found'));
            }

//    		if(!$address['number']){
//                $this->error(__('The shipping address is not bound with an ID card'));
//            }
            // 数据库事务操作
            Db::startTrans();
            try {
                // 遍历已店铺分类列表
                foreach ($lists as $item) {
                    // 1.0.6升级 修复跨店累加
                    $priceAll = 0; // 总价格
                    $supplyPriceAll = 0; // 总供应价价格
                    $numberAll = 0; // 总数量
                    $freightALL = [];
                    $coupon_price = 0; //优惠券金额
                    $discount_price = 0; // 优惠金额，因为后续版本涉及到活动减免，所以优惠金额要单独拎出来
                    // 获取店铺ID
                    $shop_id = $item['shop_id'];
                    // 查询店铺配置
                    $config = model('app\api\model\wanlshop\ShopConfig')
                        ->where('shop_id', $shop_id)
                        ->find();
                    // 如果不存在，按照累计运费
                    if (!$config) {
                        $config['freight'] = 0;
                    }
                    // 生成订单
                    $order = new \app\api\model\wanlshop\Order;
                    $order->freight_type = $config['freight'];
                    $order->user_id = $user_id;
                    $order->freight_id = $freight['id'];
                   // $order->freight_id = 24;
                    $order->shop_id = $shop_id;
                    $order->order_no = $shop_id . $user_id;
                    $order->service_ids = $item['service_ids'] ?? 0;
                    if (isset($item['remarks'])) {
                        $order->remarks = $item['remarks'];
                    }
                    // 2020年9月19日 05:30:10 新增优惠券功能
                    // 2021年3月04日 06:54:11 修改优惠券逻辑
                    $coupon = model('app\api\model\wanlshop\CouponReceive')
                        ->where(['id' => $item['coupon_id'], 'user_id' => $user_id, 'shop_id' => $shop_id])
                        ->find();
                    $order->coupon_id = $coupon ? $coupon['id'] : 0;

                    /**检测套餐**/
                    $package = model('app\api\model\wanlshop\Activity')->checkPackage($item, 'addOrder');
                    $order->activity = $package ? $package['type'] : '';
                    $order->activity_id = $package ? $package['id'] : 0;
                    $order->activity_title = $package ? $package['title'] : '';
                    $order->attachment = json_encode($params['attachment'], JSON_UNESCAPED_UNICODE);
                    $order->attachment_price = $attachment_price;
                    /**检测套餐**/
                    // 要补充活动ID
                    if ($order->save()) {
                        // 计算订单价格
                        foreach ($item['products'] as $data) {
                            // 查询商品
                            $goodsData = model('app\api\model\wanlshop\Goods')->get($data['goods_id']);
                            // 获取sku
                            $sku = model('app\api\model\wanlshop\GoodsSku')->get($data['sku_id']);

                            $sku = model('app\api\model\wanlshop\GoodsSku')->getGroupSku($sku, $data['goods_id']);

                            // 1.0.5升级 检查库存
                            if ($sku['stock'] < $data['number']) {
                                $this->error($goodsData['title'] . '-' . __('Unable to purchase, out of stock'));
                            }

                            // 库存计算方式:porder=下单减库存,payment=付款减库存
                            if ($goodsData['stock'] == 'porder') {
                                $sku->setDec('stock', $data['number']); // 1.0.3升级
                            }
                            //如果为活动商品对应修改活动库存
                            if ($sku['activity'] == 'seckill' && $sku['activity_id'] > 0) {
                                model('app\api\model\wanlshop\ActivityGoodsSku')
                                    ->where('goods_id', $data['goods_id'])
                                    ->where('activity_id', $sku['activity_id'])
                                    ->where('sku_id', $data['sku_id'])
                                    ->inc('sales', $data['number'])
                                    ->dec('stock', $data['number'])
                                    ->update();
                            }
                            // 商品列表 actual_payment
                            $goodsList[] = [
                                'order_id' => $order->id, // 获取自增ID
                                'goods_id' => $goodsData['id'],
                                'shop_id' => $shop_id,
                                'title' => $goodsData['title'],
                                'image' => $goodsData['image'],
                                'goods_sku_sn' => $sku['sn'],
                                'goods_sku_id' => $sku['id'],
                                'goods_sku_rule_id' => $sku['rule_id'],
                                'weight' => $sku['weigh'],
                                'difference' => join(',', $sku['difference']),
                                'market_price' => $sku['market_price'], // 市场价
                                'supply_price' => $sku['supply_price'], // 供货价
                                'price' => $sku['price'], // 单价
                                'discount_price' => 0, // 优惠金额
                                'actual_payment' => bcmul($sku['price'], $data['number'], 2), // 1.0.6修复 实际支付，因为要和总价进行计算
                                'number' => $data['number'],
                                'activity' => $sku['activity'], // 是否为活动商品
                                'activity_id' => $sku['activity_id'], // 是否为活动商品
                            ];
                            $priceAll = bcadd($priceAll, bcmul($sku['price'], $data['number'], 2), 2); // 计算价格
                            $supplyPriceAll = bcadd($supplyPriceAll, bcmul($sku['supply_price'], $data['number'], 2), 2); // 计算价格
                            $numberAll += $data['number']; // 计算数量
                        }
                        $packageFright = model('app\api\model\wanlshop\Package')->packageFright($goodsList, $freight['id'], $address['city']);
                        $freightPrice = $packageFright['freightPrice'];
                        // 计算运费叠加方案
                        $freightData = [
                            'id' => $freight['id'],
                            'name' => $freight['name'],
                            'price' => $freightPrice
                        ];
                        /**如果是套餐就修改订单金额**/
                        $priceAll = $package ? $package['price'] : $priceAll;
                        /**如果是套餐就修改订单金额**/
                        $freight_price = $freightData['price'];  //快递金额
                        $price = bcadd($priceAll, $freight_price, 2); // 总价格
                        //计算增值服务价格
                        $servicePrice = model('app\api\model\wanlshop\Orderservice')
                            ->where('id', 'in', $item['service_ids'] ?? 0)
                            ->sum('price');
                        if ($servicePrice > 0) {
                            $price = bcadd($price, $servicePrice, 2); // 总价格 + 增值服务
                        }
                        if ($attachment_price > 0) {
                            $price = bcadd($price, $attachment_price, 2); // 总价格 + 增值服务
                        }
                        // 如果优惠券存在
                        if ($coupon)
                            list($price, $coupon_price, $freight_price, $discount_price, $goodsList)
                                = $this->coupon($coupon, $goodsList, $priceAll, $freight_price, $order->id);
                        // 生成支付

                        $currency_rate = model('app\api\model\wanlshop\Pay')->getCurrencyRate('', 0);
                        $currency_rate = $currency_rate ? $currency_rate : 0; // 获取商家设置的汇率
                        $payList[] = [
                            'user_id' => $user_id,
                            'shop_id' => $shop_id,
                            'order_id' => $order->id,
                            'order_no' => $order->order_no,
                            'pay_no' => model('app\api\model\wanlshop\Pay')->getPayNo($order->order_no),
                            'price' => $price <= 0 ? 0.01 : $price,  // 支付价格，系统要求至少支付 一分钱
                            'currency_rate' => $currency_rate,
                            'rmb_price' => bcmul($price <= 0 ? 0.01 : $price, $currency_rate, 2),
                            'order_price' => $priceAll, // 订单总金额
                            'supply_price' => $supplyPriceAll, // 订单总金额
                            'coupon_price' => $coupon_price,  // 优惠券金额
                            'freight_price' => $freight_price, // 快递费
                            'discount_price' => $discount_price, // 优惠金额
                            'attachment_price' => $attachment_price,//附件金额
                            'number' => $numberAll
                        ];
                        // 生成地址
                        $addressList[] = [
                            'user_id' => $user_id,
                            'shop_id' => $shop_id,
                            'order_id' => $order->id,
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'address' => $address['province'] . '/' . $address['city'] . '/' . $address['district'] . '/' . $address['address'],
                            'address_name' => $address['address_name'],
                            'location' => $address['location'],
                            'image_front' => $address['image_front'],
                            'image_back' => $address['image_back'],
                            'number' => $address['number'],
                        ];
                    } else {
                        $this->error(__('Failed to create order because network is busy'));
                    }
                }
                model('app\api\model\wanlshop\OrderAddress')->saveAll($addressList);
                model('app\api\model\wanlshop\OrderGoods')->saveAll($goodsList);
                $result = model('app\api\model\wanlshop\Pay')->saveAll($payList);
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success('返回成功', $result);
            } else {
                $this->error(__('Order abnormal, please return to reorder'));
            }
        } else {
            $this->error(__('Illegal request'));
        }
    }

    // 检测订单状态
    public function checkOrderStatus()
    {
        $id = $this->request->post('id');
        $id ? $id : ($this->error(__('Illegal request')));
        $state = $this->getOrderState($id);
        if ($state > 1) {
            $this->success('支付成功', ['status' => 'success']);
        } else {
            $this->success('未支付', ['status' => 'faild']);
        }
    }

    /**
     * 订单状态码（方法内使用）
     *
     * @ApiSummary  (WanlShop 返回订单状态码)
     * @ApiMethod   (POST)
     *
     * @param string $id 订单ID
     */
    private function getOrderState($id = 0)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $order = model('app\api\model\wanlshop\Order')
            ->where(['id' => $id, 'user_id' => $this->auth->id])
            ->find();
        return $order['state'];
    }

    /**
     * 获取优惠券后金额 内部方法
     * 1.0.5升级
     * @param string $coupon 优惠券数据
     * @param string $goodsList 商品列表
     * @param string $priceAll 订单总价格
     * @param string $freight_price 运费价格
     * @param string $order_id 订单ID
     */
    private function coupon($coupon = [], $goodsList = [], $priceAll = 0, $freight_price = 0, $order_id = 0)
    {
        // 判断是否可用
        if ($priceAll >= $coupon['limit']) {
            if ($coupon['type'] == 'reduction' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'reduction')) {
                $coupon_price = $coupon['price'];
            }
            if ($coupon['type'] == 'discount' || ($coupon['type'] == 'vip' && $coupon['usertype'] == 'discount')) {
                // 排除异常折扣，还原百分之
                $discount = $coupon['discount'] > 10 ? bcdiv($coupon['discount'], 100, 2) : bcdiv($coupon['discount'], 10, 2);
                // 优惠金额 = 订单金额 - 订单金额 * 折扣
                $coupon_price = bcsub($priceAll, bcmul($priceAll, $discount, 2), 2);
            }
            if ($coupon['type'] == 'shipping') {
                $coupon_price = $freight_price;
                $freight_price = 0;
            }
            // 总优惠金额
            $paycoupon = 0;
            // 总实际支付金额
            $payment = 0;
            // 更新商品列表
            $newGoodsList = [];
            foreach ($goodsList as $row) {
                $price = bcmul($row['price'], $row['number'], 2);
                $discount_price = round($coupon_price * ($price / $priceAll), 2); // 优惠金额
                $actual_payment = $price - $discount_price; // 实际支付
                $row['discount_price'] = $discount_price;
                $row['actual_payment'] = $actual_payment;
                $paycoupon += $discount_price;
                $payment += $actual_payment;
                $row['freight_price'] = $freight_price;
                $newGoodsList[] = $row;
            }
            // 更新已使用数量
            model('app\api\model\wanlshop\Coupon')
                ->where(['id' => $coupon['coupon_id']])
                ->setInc('usenum');
            // 修改该优惠券状态 已用
            $coupon->allowField(true)->save(['state' => 2]);
            //总金额 = 总优惠后金额 + 运费
            return [bcadd($payment, $freight_price, 2), $paycoupon, $freight_price, $paycoupon, $newGoodsList];
        } else {
            model('app\api\model\wanlshop\Order')->destroy($order_id);
            $this->error('订单金额' . $priceAll . '元，不满' . $coupon['limit'] . '元');
        }
    }


    /**
     * 获取运费模板和子类 内部方法
     * @param string $id 运费ID
     * @param string $weigh 商品重量
     * @param string $number 商品数量
     * @param string $city 邮递城市
     */
    private function freight($id = null, $weigh = null, $number = 0, $city = null)
    {
        if (!$id) { // 如果id为0则为自提,默认返回数据
            return [
                'id' => 0,
                'name' => 0,
                'price' => 0,
                'isdelivery' => 0,
            ];
        }
        // 运费模板
        $data = model('app\api\model\wanlshop\ShopFreight')->where('id', $id)->field('id,delivery,isdelivery,name,valuation')->find();
        $data['price'] = 0;
        // 是否包邮:0=自定义运费,1=卖家包邮
        if ($data['isdelivery'] == 0) {
            // 获取地址编码
            $area = model('app\common\model\Area')->where('name', $city)->find();
            $list = model('app\api\model\wanlshop\ShopFreightData')
                ->where('citys', 'like', '%' . $area['id'] . '%')
                ->where('freight_id', $id)
                ->find();
            // 查询是否存在运费模板数据
            if (!$list) {
                $list = model('app\api\model\wanlshop\ShopFreightData')
                    ->where('freight_id', $id)
                    ->find();
            }
            // 计价方式:0=按件数,1=按重量,2=按体积  1.0.2升级
            if ($data['valuation'] == 0) {
                if ($number <= $list['first']) {
                    $price = $list['first_fee'];
                } else {
                    $additional = $list['additional'] > 0 ? $list['additional'] : 1; //因为要更换vue后台，临时方案，为防止客户填写0
                    $price = bcadd(bcmul(ceil(($number - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
                }
            } else {
                $weigh = $weigh * $number; // 订单总重量
                if ($weigh <= $list['first']) { // 如果重量小于等首重，则首重价格
                    $price = $list['first_fee'];
                } else {
                    $additional = $list['additional'] > 0 ? $list['additional'] : 1;
                    $price = bcadd(bcmul(ceil(($weigh - $list['first']) / $additional), $list['additional_fee'], 2), $list['first_fee'], 2);
                }
            }
            $data['price'] = $price;
        }
        return $data;
    }

    public function replenishorder(){
        $image_front = $this->request->post('image_front');
        $image_back = $this->request->post('image_back');
        $order_id  = $this->request->post('order_id');
        Db::name('wanlshop_order')->where('id',$order_id)->update([
            'idcard_status'=>1
        ]);
        Db::name('wanlshop_order_address')->where('order_id',$order_id)->update([
            'image_front'=>$image_front,
            'image_back'=>$image_back,
        ]);
        $this->success('');
    }

}